import { Button, NavBar, Form, Input, Toast } from "antd-mobile";
import { InputRef } from "antd-mobile/es/components/input";
import type { AxiosError } from "axios";
import { useEffect, useRef, useState } from "react";
import { useDispatch } from "react-redux";
import { useHistory, useLocation } from "react-router-dom";
import { login, getCode } from "@/store/actions/login";

import styles from "./index.module.scss";

type LoginForm = { mobile: string; code: string };

const Login = () => {
    const history = useHistory();
    const dispatch = useDispatch();
    const location = useLocation<{ from: string } | undefined>();
    const [form] = Form.useForm();
    // 创建获取手机号的 ref 对象
    const mobileRef = useRef<InputRef>(null);
    // 储存倒计时
    const [timeLeft, setTimeLeft] = useState(0);
    // 定时器
    const timerRef = useRef(-1);
    // 登录
    const onFinish = async (values: LoginForm) => {
        try {
            await dispatch(login(values));
            // 登录成功后的操作
            Toast.show({
                content: "登录成功",
                duration: 800,
                afterClose: () => {
                    if (location.state) {
                        return history.replace(location.state.from);
                    }
                    history.replace("/home/index");
                },
            });
        } catch (e) {
            const error = e as AxiosError<{ message: string }>;
            // console.log('登录失败')
            // console.dir(e)
            Toast.show({
                content: error.response?.data.message,
                duration: 1000,
            });
        }
    };

    // 发送验证码
    const onGetCode = () => {
        // 设置倒计时时间
        setTimeLeft(60);
        timerRef.current = window.setInterval(() => {
            setTimeLeft((timeLeft) => timeLeft - 1);
        }, 1000);
        const mobile = (form.getFieldValue("mobile") ?? "") as string;
        const hasError = form.getFieldError("mobile").length > 0;
        if (mobile.trim() === "" || hasError) {
            return mobileRef.current?.focus();
        }
        // 表单验证成功，获取验证码
        // 发送请求，根据 手机号 来获取验证码
        dispatch(getCode(mobile));
        Toast.show({
            content: "验证码已发送",
            duration: 600,
        });
    };
    useEffect(() => {
        // console.log('当前剩余时间：', timeLeft)
        if (timeLeft === 0) {
            // 清理定时器
            window.clearInterval(timerRef.current);
        }
    }, [timeLeft]);
    // 作用：在组件卸载时，清理定时器
    useEffect(() => {
        return () => {
            window.clearInterval(timerRef.current);
        };
    }, []);
    return (
        <div className={styles.root}>
            <NavBar onBack={() => history.go(-1)}></NavBar>

            <div className="login-form">
                <h2 className="title">账号登录</h2>
                <Form
                    form={form}
                    onFinish={onFinish}
                    initialValues={{
                        // 注意 mobile 是字符串类型！！！
                        mobile: "1391111111",
                        code: "24681",
                    }}>
                    <Form.Item
                        className="login-item"
                        name="mobile"
                        // validateTrigger="onBlur"
                        rules={[
                            {
                                required: true,
                                message: "请输入手机号",
                            },
                            {
                                message: "手机号格式错误",
                                pattern: /^1[3-9]\d{9}$/,
                            },
                        ]}>
                        <Input
                            ref={mobileRef}
                            placeholder="请输入手机号"
                            autoComplete="off"
                            maxLength={11}
                        />
                    </Form.Item>

                    <Form.Item
                        name="code"
                        className="login-item"
                        extra={
                            <span
                                className="code-extra"
                                onClick={
                                    timeLeft === 0 ? onGetCode : undefined
                                }>
                                {timeLeft === 0
                                    ? "发送验证码"
                                    : `${timeLeft}s后重新获取`}
                            </span>
                        }
                        rules={[
                            { required: true, message: "请输入验证码" },
                            {
                                pattern: /^\d{6}$/,
                                message: "验证码格式错误",
                            },
                        ]}>
                        <Input
                            placeholder="请输入验证码"
                            autoComplete="off"
                            maxLength={6}
                        />
                    </Form.Item>

                    {/* noStyle 表示不提供 Form.Item 自带的样式 */}
                    <Form.Item noStyle shouldUpdate>
                        {() => {
                            // 得到禁用状态
                            const disabled =
                                form
                                    .getFieldsError()
                                    .filter((item) => item.errors.length > 0)
                                    .length > 0 || !form.isFieldsTouched(true);

                            return (
                                <Button
                                    disabled={disabled}
                                    block
                                    type="submit"
                                    color="primary"
                                    className="login-submit">
                                    登 录
                                </Button>
                            );
                        }}
                    </Form.Item>
                </Form>
            </div>
        </div>
    );
};

export default Login;
